/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.dabarobjects.mobile.database;

import com.dabarobjects.mobile.utils.madex.MadexParserUtils;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;

/**
 * A Data Series allows a user to hash a group of items within a particular key type within the storage
 * @author DabarObjects Solutions Limited (www.dabarobjects.com)
 */
public class DataSeries extends Hashtable {

    private int maxSize;
    private MadexDBMS databaseRef;
    private String seriesName;

    public DataSeries(int maxSize, MadexDBMS databaseRef, String seriesName) {
        this.maxSize = maxSize;
        this.databaseRef = databaseRef;
        this.seriesName = seriesName;
        updating = false;
    }
    private boolean updating;
    private int indexSequence;

    public DataSeries(MadexDBMS databaseRef, String seriesName, int indexSequence) {
        this.databaseRef = databaseRef;
        this.seriesName = seriesName;
        this.indexSequence = indexSequence;
        updating = true;
    }

    public final void addRecord(String key, Object data) {
        put(key, data);
    }

    public synchronized void commitSave() {
        if (updating) {
            commitUpdate();
            return;
        }
        String rowNotStr = asNotation();
        databaseRef.addRow(seriesName, rowNotStr);
        close();
    }

    public synchronized void commitUpdate() {
        if (!updating) {
            return;
        }
        String rowNotStr = asNotation();
        databaseRef.updateRow(seriesName, rowNotStr, indexSequence);
        close();
    }

    public final Object put(Object key, Object value) {
        if (size() <= maxSize) {
            if (value instanceof String) {
                return super.put(key, value);
            }
            if (value instanceof Date) {
                return super.put(key, MadexParserUtils.dateAsString((Date) value));
            }
            if (value instanceof Integer) {
                return super.put(key, value);
            }
            return super.put(key, value);

        } else {
            return null;
        }


    }

    public String asNotation() {
        String not = MadexParserUtils.hashTableToString(this, "{", "}");

        return not;
    }

    public void close() {
        Enumeration em = keys();
        while (em.hasMoreElements()) {
            put(em.nextElement(), null);
        }
        clear();

    }
}
